<template>
  <el-form ref="ruleForm"
           :model="form"
           label-width="90px"
           label-position="right"
           size="small"
           :rules="rules">
    <el-row>
      <el-form-item label="收货方"
                    prop="consigneeName"
                    :rules="[
                {
                  required: true,
                  message: `收货方不存在`,
                  validator: validateConsignee,
                  trigger: 'change'
                }
              ]">
        <el-select id="consigneeNameLimit"
                   v-model="form.consigneeName"
                   clearable
                   placeholder="请选择收货方"
                   style="width: 100%"
                   filterable
                   :allow-create="true"
                   @input="changeConsignee">
          <el-option v-for="({name}, index) in consigneeArr"
                     :key="index"
                     :label="name"
                     :value="name">
          </el-option>
        </el-select>
      </el-form-item>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="联系人"
                      prop="toContactName">
          <el-input v-model="form.toContactName"
                    maxlength="20" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系电话"
                      prop="toContactMobile">
          <el-input v-model="form.toContactMobile"
                    maxlength="50" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="flex-start">
          <el-form-item label="收货地"
                        prop="toArea"
                        :rules="[
                {
                  required: true,
                  message: `${form.toArea.districtName ? '收货地错误':'请选择收货地'}`,
                  validator: validateToArea,
                  trigger: 'change'
                }
              ]">
            <area-select v-model="form.toArea"
                         class="w300r"
                         align="center"
                         :area-value.sync="form.toArea"
                         @confirm="selectToArea" />
            <!-- <area-cascader v-model="form.toArea"
                           class="w300r"
                           :props="props"
                           @input="selectToArea" /> -->
          </el-form-item>
          <el-form-item prop="toAddress"
                        :label-width="'0px'"
                        :rules="[
                {
                  required: true,
                  message: `${form.toAddress ? '详细地址最多输入100个字符':'请输入详细地址'}`,
                  validator: validateToAddress,
                  trigger: 'blur'
                }
              ]">
            <el-input v-model="form.toAddress"
                      class="w410r"
                      placeholder="请输入详细地址"
                      maxlength="100" />
          </el-form-item>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="时效"
                      prop="days"
                      :rules="[
                {
                  required: true,
                  message: `请选择时效`,
                  validator: validateDays,
                  trigger: ['change', 'blur']
                }
              ]">
          <el-select v-model="form.days"
                     style="width: 100%"
                     :placeholder="`请选择时效`"
                     @change="receivingDays">
            <el-option :value="0"
                       label="当天">当天</el-option>
            <el-option v-for="i in 30"
                       :key="i"
                       :value="i">{{ i }}天</el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="收货时间"
                      prop="toTime"
                      :rules="[
                {
                  required: true,
                  message: `${form.toTime ? '收货时间格式错误' : '请选择收货时间'}`,
                  validator: validateToTime,
                  trigger: 'change'
                }
              ]">
          <el-date-picker v-model="form.toTime"
                          align="left"
                          style="width: 100%"
                          type="datetime"
                          placeholder="请选择收货时间"
                          format="yyyy-MM-dd HH:mm"
                          popper-class="no-atTheMoment"
                          :default-time="'23:59:59'"
                          :picker-options="pickerOptions"
                          @change="changeTime"></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import AreaSelect from "./AreaSelect.vue";
import validateForm from "./validateForm.js";
import { consignee } from "@/api/index";
import { getDiffDays, returnCompareTime } from "@/libs/util.js";
export default {
  name: "Consignee",
  components: {
    AreaSelect
  },
  mixins: [validateForm],
  props: {
    record: {
      type: Object,
      default: () => { }
    },
    systemBillObj: {
      type: Object,
      default: () => { }
    },
    customerName: String,
    mofidyFromTime: String
  },
  data () {
    return {
      rules: {
        consigneeName: [{ required: true, message: "请输入收货方名称", trigger: "blur" }],
        toContactName: [{ required: true, message: "请输入收货联系人", trigger: "blur" }],
        toContactMobile: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        toAddress: [{ required: true, message: "请输入收货地址", trigger: "blur" }],
        // days: [{ required: true, message: "请选择时效", trigger: ['change', 'blur'] }],
        toTime: [{ required: true, message: "请选择收货时间", trigger: "change" }],
      },
      props: {
        label: 'name',
        value: 'areaCode',
        checkStrictly: true
      },
      form: {
        consigneeName: null,
        toContactName: null,
        toContactMobile: null,
        toArea: {
          districtName: null,
          provinceName: null,
          cityName: null
        },
        toAddress: null,
        days: null,
        toTime: null,
      },
      fromTime: null,
      consigneeArr: [], // 收货方
      consigneeFlag: true, //收货方不存在
      toTimeFlag: true, //收货时间错误
      toAreaFlag: true, //收货地错误
      errors: []
    };
  },
  computed: {
    filter () {
      return {
        size: 9999,
        customerName: this.customerName,
      }
    },
    pickerOptions () {
      return {
        // 时间选择限制 收货时间
        disabledDate: (time) => {
          if (this.systemBillObj.billDateFlag) {
            let toTimeInit = returnCompareTime(
              new Date(this.$moment(this.fromTime).format("YYYY-MM-DD HH:mm:ss")),
              new Date(this.$moment(this.systemBillObj.sameMonthDay).format("YYYY-MM-DD 23:59:59"))
            ) ? this.fromTime : this.systemBillObj.sameMonthDay;
            return (
              time.getTime() <=
              new Date(
                new Date(toTimeInit).setDate(
                  new Date(toTimeInit).getDate() - 1
                )
              ).getTime()
            );
          } else if (this.fromTime) {
            return (
              time.getTime() <=
              new Date(
                new Date(this.fromTime).setDate(
                  new Date(this.fromTime).getDate() - 1
                )
              ).getTime()
            );
          } else {
            return (
              time.getTime() <=
              new Date(
                new Date(this.systemBillObj.lastMonthDay).setDate(
                  new Date(this.systemBillObj.lastMonthDay).getDate() - 1
                )
              ).getTime()
            );
          }
        },
      }
    }
  },
  watch: {
    customerName (val) {
      this.form.consigneeName = null;
      this.loadConsignee();
    },
    mofidyFromTime (val) {
      this.fromTime = val;
      if (val) {
        if (this.form.days || this.form.days === 0) {
          this.form.toTime = this.$moment(this.fromTime).add(this.form.days, "days").format("YYYY-MM-DD 23:59");
        } else {
          this.form.toTime = null;
        }
      } else {
        this.form.days = null;
        this.form.toTime = null;
      }
    }
  },
  created () {
    this.loadConsignee();
    this.form = {
      consigneeName: this.record.consigneeName,
      toContactName: this.record.toContactName,
      toContactMobile: this.record.toContactMobile,
      toArea: {
        districtName: this.record.toDistrict,
        provinceName: this.record.toProvince,
        cityName: this.record.toCity,
      },
      toAddress: this.record.toAddress,
      toTime: this.record.toTime
    }
    this.fromTime = this.record.fromTime;
    this.errors = this.record?.errors || [];
    if (this.errors && this.errors.length) {
      this.errors.map(item => {
        if (item.field === "fromTime") {
          this.fromTime = null;
        }
        if (item.field === "toTime") {
          this.form.toTime = null;
        }
      })
    }
    if (this.fromTime && this.form.toTime) {
      this.form.days = getDiffDays(
        this.$moment(this.fromTime).format("YYYY-MM-DD"),
        this.$moment(this.form.toTime).format("YYYY-MM-DD")
      );
    }
  },
  mounted () {
    this.dom();
    this.validateForm();
  },
  methods: {
    dom () {
      const input = document.querySelector("#consigneeNameLimit");
      input.setAttribute("maxLength", 80);
    },
    // 校验规则
    validateForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          return true;
        } else {
          return false;
        }
      });
    },
    async loadConsignee () {
      if (!this.customerName) return false;
      let { code, data } = await consignee.search(this.filter);
      if (code !== 0 || !data) return;
      this.consigneeArr = data.records || [];
    },
    changeConsignee (val) {
      if (val) {
        this.consigneeArr.map(item => {
          if (item.name === val) {
            this.form.toContactMobile = item.contactMobile;
            this.form.toContactName = item.contactName;
          }
        })
        this.consigneeFlag = false;
      }
    },
    changeTime (val) {
      if (val) {
        this.form.toTime = this.$moment(val).format("YYYY-MM-DD HH:mm");
        this.toTimeFlag = false;
        if (this.fromTime) {
          this.form.days = getDiffDays(
            this.$moment(this.fromTime).format("YYYY-MM-DD"),
            this.$moment(this.form.toTime).format("YYYY-MM-DD")
          );
        }
      } else {
        this.form.days = null;
      }
      this.$emit("updateToTime", val)
    },
    receivingDays (val) {
      if ((val || val === 0) && this.fromTime) {
        this.form.toTime = this.$moment(this.fromTime).add(val, "days").format("YYYY-MM-DD 23:59");
        this.toTimeFlag = false;
      }
      this.$forceUpdate();
    },
    // 地区
    selectToArea (val) {
      this.form.toArea = Object.assign(this.form.toArea, val);
      this.form.toCity = val.cityName;
      this.form.toDistrict = val.districtName;
      this.form.toProvince = val.provinceName;
      this.toAreaFlag = false;
    },
  }
};
</script>

<style lang="scss" scoped>
.no-atTheMoment
  .el-picker-panel__footer
  .el-button--text.el-picker-panel__link-btn {
  display: none !important;
}
.flex-start {
  display: flex;
  justify-content: flex-start;
}
.w300r {
  width: 300px !important;
}
.w410r {
  width: 410px !important;
}
</style>
